import { loadApps } from '../application/apps'
import { originalPushState, originalReplaceState, originalWindow, originalWindowAddEventListener } from './originalEnv'

// 覆盖 History方法 根据当前 url 加载或卸载 app
export default function overwriteEventsAndHistory() {
    // 重写 window.history.pushState 方法
    originalWindow.history.pushState = function (state: any, title: string, url: string) {
        const result = originalPushState.call(this, state, title, url)
        loadApps()
        return result
    }
    
    // 重写 window.history.replaceState 方法
    originalWindow.history.replaceState = function (state: any, title: string, url: string) {
        const result = originalReplaceState.call(this, state, title, url)
        loadApps()
        return result
    }
    
    // 浏览器前进或后退
    originalWindowAddEventListener.call(originalWindow, 'popstate', () => {
        loadApps()
    }, true)
    
    // hash是URL中#后面那部分，同时修改hash值不会引起页面的刷新
    originalWindowAddEventListener.call(originalWindow, 'hashchange', () => {
        loadApps()
    }, true)
}
